#
# Classes related to actually playing games with the FGS client.
#

from xmlrpclib import Fault,ProtocolError
from Exception_ import FgsException

class Game(object):
    def __init__(self, portal, cache, **kwargs):
        self.portal = portal
        self._cache = cache
        self._proxy = portal._proxy
        for k,v in kwargs.items():
            if k.startswith("game_"):
                k = k[5:]
            self.__dict__[k] = v

    def __getattr__(self, name):
        if name == "servers":
            self.__dict__['servers'] = self._get_servers()
            return self.__dict__['servers']
        elif name == "logo_path":
            return self._get_logo_path()
        else:
            raise AttributeError

    def clear(self):
        del self.__dict__['servers']

    def _get_logo_path(self):
        if self.logo_hash == '':
            return False

        # Ask the cache if it has the right logo
        logo = self._cache.retrieve_file_path(self.logo_hash)
        if logo:
            return logo

        # If the cache doesn't have it, retrieve it from the portal.
        try:
            logo_data = self._proxy.user.getgamelogo(self.logo_hash)
        except Fault,f:
            raise FgsException("XmlRPC call faulted: %s" % f.faultString)
        except ProtocolError, p:
            raise FgsException("Transport error during XmlRpc call on %s: %s" % (p.errmsg, p.url))

        from base64 import decodestring
        logo_data = decodestring(logo_data['logo'])

        if self._cache.cache_enabled():
            # Store the data in cache and return it
            self._cache.store_file(logo_data, self.logo_hash)
            return self._cache.retrieve_file_path(self.logo_hash)
        else:
            # Fallback when no cache is available.
            from os.path import join
            from os import getcwd
            file_path = join(getcwd(), self.logo_hash)
            f = file(file_path, 'w')
            f.write(logo_data)
            f.close()
            return file_path

    def _get_servers(self):
        servers = []
        try:
            server_list = self._proxy.user.getserverlist(self.id)
        except Fault, f:
            raise FgsException("XmlRpc call faulted: %s" % f.faultString)
        except ProtocolError, p:
            raise FgsException("Transport error during XmlRpc call on %s: %s" % (p.errmsg, p.url))

        for server in server_list:
            servers.append(Server(self, **server))

        return dict([(x,servers[x]) for x in range(len(servers))])


class Server(object):
    def __init__(self, game, **kwargs):
        self.game = game
        for k,v in kwargs.items():
            if k.startswith("game_"):
                k = k[5:]
            self.__dict__[k] = v
